//间接mutation更新state的多个方法的对象
import {
  RECEIVE_ADDRESS,
  RECEIVE_CATEGORYS,
  RECEIVE_SHOPS,
  RECEIVE_USER_INFO,
  RESET_USER_INFO,
  RECEIVE_GOODS,
  RECEIVE_RATINGS,
  RECEIVE_INFO,
  INCREMENT_FOOD_COUNT,
  DECREMENT_FOOD_COUNT,
  CLEAR_CART,
  RECEIVE_SEARCH_SHOPS
} from './mutation-types'

import {
  reqAddress,
  reqFoodCategorys,
  reqShops,
  reqUserInfo,
  reqLogout,
  reqShopRatings,
  reqShopGoods,
  reqShopInfo,
  reqSearchShop
} from '../api'


export default {
  //异步获取数据
  async getAddress({commit, state}) {//获取地址

    //发送ajax请求
    const geohash = state.latitude + ',' + state.longitude
    let result = await reqAddress(geohash);

    //提交一个commit
    if (result.code === 0) {
      let address = result.data;
      commit(RECEIVE_ADDRESS, {address})
    }
  },
  async getFoodCategorys({commit}) {//获取食品分类

    //发送ajax请求
    let result = await reqFoodCategorys();

    //提交一个commit
    if (result.code === 0) {
      const categorys = result.data
      commit(RECEIVE_CATEGORYS, {categorys})
    }
  },
  async getShops({commit, state}) {//获取商铺列表

    //发送ajax请求
    const {latitude, longitude} = state
    let result = await reqShops(longitude, latitude);

    //提交一个commit
    if (result.code === 0) {
      const shops = result.data
      commit(RECEIVE_SHOPS, {shops})
    }
  },

  //同步记录用户信息
  recordUser({commit}, userInfo) {
    commit(RECEIVE_USER_INFO, {userInfo})
  },

  // 异步获取用户信息
  async getuserInfo({commit}) {

    let result = await reqUserInfo();
    if (result.code === 0) {
      let userInfo = result.data;
      commit(RECEIVE_USER_INFO, {userInfo})

    }
  },
//异步登出
  async logout({commit}) {
    let result = await reqLogout();
    if (result.code === 0) {
      commit(RESET_USER_INFO)
    }
  },

  //获取商品数据
  async getShopGoods({commit}, callBack) {
    let result = await reqShopGoods();
    if (result.code === 0) {
      let goods = result.data;
      commit(RECEIVE_GOODS,{goods})
      callBack() && callBack()
    }
  },

  //同步更新food中的count值
  updateFoodCount({commit},{isAdd,food}){
    if (isAdd){
      commit(INCREMENT_FOOD_COUNT,{food})
    }else {
      commit(DECREMENT_FOOD_COUNT,{food})
    }
  },
  async getShopInfo({commit}) {
    let result = await reqShopInfo();
    if (result.code === 0) {
      let info = result.data;
      commit(RECEIVE_INFO,{info})
    }
  },

  async getShopRatings({commit}) {
    let result = await reqShopRatings();
    if (result.code === 0) {
      let rating = result.data;
      commit(RECEIVE_RATINGS,{rating})
    }
  },




}

